/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo18.service;

import cn.edu.zua.demo18.entity.SysRole;
import cn.edu.zua.demo18.entity.SysUser;
import cn.edu.zua.demo18.jpa.SysUserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/30 15:13
 */
@Service
public class Chapter18UserDetailServiceImpl implements UserDetailsService {
    private SysUserJpa userJpa;

    @Autowired
    public Chapter18UserDetailServiceImpl(SysUserJpa userJpa) {
        this.userJpa = userJpa;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(String userName) {
        String lowerUserName = userName.toLowerCase();
        SysUser sysUser = userJpa.findByUserNameCaseInsensitive(userName);
        if (sysUser == null) {
            throw new UsernameNotFoundException("User " + lowerUserName + " was not found in the database");
        }
        // 获取用户的所有权限并且SpringSecurity需要的集合
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (SysRole role : sysUser.getRoleSet()) {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
            grantedAuthorityList.add(grantedAuthority);
        }
        // 返回一个SpringSecurity需要的用户对象
        return new User(sysUser.getUserName(), sysUser.getUserPassword(), grantedAuthorityList);
    }
}
